//
//  RadioButtonsView.m
//  ECBBusinessCamp
//
//  Created by rimi on 16/6/17.
//  Copyright © 2016年 邓毕华. All rights reserved.
//

#import "RadioButtonsView.h"

#define BUTTON_W SCREEN_WIDTH * 0.08

@implementation RadioButtonsView

#pragma mark 🌷🌷🌷life cycle🌷🌷🌷
- (instancetype)initWithNames:(NSArray *)titleNames selectedIndex:(SelectIndexBlock)selectedIndex
{
    self = [super init];
    if (self) {
        self.backgroundColor = [UIColor whiteColor];
        _selecIndexBlock = selectedIndex;
        
        // 默认第一个按钮处于选中状态
        _selecIndex = 10;
        
        for (NSInteger i = 0; i < titleNames.count; i++) {
            UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
            button.frame = CGRectMake(i * BUTTON_W + (i - 1) * SCREEN_WIDTH * 0.02, 0, BUTTON_W, BUTTON_W * 0.5);
            // 设置默认状态下的背景图片
            [button setBackgroundImage:[UIImage imageNamed:@"enjoy_btn_normal.png"] forState:UIControlStateNormal];
            // 设置选中状态下的背景图片
            [button setBackgroundImage:[UIImage imageNamed:@"enjoy_btn_select.png"] forState:UIControlStateSelected];
            // 设置 tag
            button.tag = i + 10;
            // 设置标题
            [button setTitle:titleNames[i] forState:UIControlStateNormal];
            // 设置标题颜色
            [button setTitleColor:RGB_COLOR(144, 144, 144, 1) forState:UIControlStateNormal];
            // 设置标题字体
            button.titleLabel.font = [UIFont systemFontOfSize:24];
            // 添加事件
            [button addTarget:self action:@selector(respondsToSelecIndex:) forControlEvents:UIControlEventTouchUpInside];
            [self addSubview:button];
        }
        
        // 将第一个按钮选中
        UIButton * selectBtn = [self viewWithTag:10];
        selectBtn.selected = YES;
    }
    return self;
}

#pragma mark 🌷🌷🌷event response🌷🌷🌷
- (void)respondsToSelecIndex:(UIButton *)sender {
    // 重复选中不做任何操作
    if (sender.tag == _selecIndex) {
        return;
    }
    
    // 将前一个选中按钮取消选中
    UIButton * selectBtn = [self viewWithTag:_selecIndex];
    selectBtn.selected = NO;
    // 将现在点击的按钮选中
    sender.selected = YES;
    // 记录现在选中的按钮tag
    _selecIndex = sender.tag;
    
    // block回调 传回选中的是第几个按钮
    _selecIndexBlock(sender.tag - 10);
}

@end
